package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.transaction.Transactional;

import br.urca.dao.AlunosCursoDAO;
import br.urca.model.AlunoCurso;

@Transactional
public class JPAAlunosCursoDAO implements AlunosCursoDAO {
	
	private EntityManager manager;
	
	public JPAAlunosCursoDAO() {
		this(null);
	}
	
	@Inject
	public JPAAlunosCursoDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<AlunoCurso> todos() {
		return this.manager.createQuery("SELECT a FROM AlunoCurso a", AlunoCurso.class)
				.getResultList();
	}

	@Override
	public AlunoCurso buscaPorMatricula(String matricula) {
		try {
			return this.manager.createQuery("SELECT a FROM AlunoCurso a WHERE a.matricula = :matricula"
					, AlunoCurso.class)
					.setParameter("matricula", matricula).getSingleResult();
		} catch(NoResultException e) {
			return null;
		}
	}

	@Override
	public AlunoCurso buscaDadosAluno(String matricula, String senha) {
		try {
			return this.manager.createQuery("SELECT a FROM AlunoCurso a "
					+ "WHERE a.matricula = :matricula "
					+ "AND a.senha = :senha"
					, AlunoCurso.class)
					.setParameter("matricula", matricula)
					.setParameter("senha", senha)
					.getSingleResult();
		} catch(NoResultException e) {
			return null;
		}
	}

	@Override
	public AlunoCurso buscaPorId(Long id) {
		try {
			return this.manager.createQuery("SELECT a FROM AlunoCurso a WHERE a.aluno.id = :id"
					, AlunoCurso.class)
					.setParameter("id", id).getSingleResult();
		} catch(NoResultException e) {
			return null;
		}
	}

	@Override
	public void salvar(AlunoCurso alunoCurso) {
		if (alunoCurso.getMatricula() == null) {
			//gerarIdAluno(aluno);
			//this.manager.persist(alunoCurso);
		} else {
			this.manager.merge(alunoCurso);
		}
	}

	@Override
	public AlunoCurso buscaMatriculaSenha(String cpf, String rg) {
		try {
			return this.manager.createQuery("SELECT a FROM AlunoCurso a "
					+ "WHERE a.aluno.cpf = :cpf AND a.aluno.rg = :rg "
					, AlunoCurso.class)
					.setParameter("cpf", cpf)
					.setParameter("rg", rg).getSingleResult();
		} catch(NoResultException e) {
			return null;
		}
	}

}
